import mongoose from "mongoose";
import { Menu } from "../models/menu";

export default async function sys(app) {
  app.get("list", () => {
    return Menu.find({}).sort({ order: 1 });
  });
  app.post("delete", async (req) => {
    const { id, index } = req.body;
    const find = await Menu.findById(id);
    find.children = find.children.filter((item, i) => i !== index);
    await find.save();
    return find;
  });
  app.post("update", async (req) => {
    const { id, index, ...rest } = req.body;
    if (typeof index !== "undefined") {
      const res = await Menu.updateOne(
        { _id: id },
        {
          $set: {
            [`children.${index}`]: rest,
          },
        }
      );
      return res;
    } else {
      await Menu.updateOne({ _id: id }, rest);
    }
    return { id };
  });
  app.post("add", async (req) => {
    const { id, ...rest } = req.body;
    return Menu.updateOne(
      { _id: id },
      {
        $push: {
          children: rest,
        },
      }
    );
  });
}

export const autoPrefix = "/menu/";
